import { useState, useEffect } from 'react';
// import {fetchRequest} from '@api/http'
type UseFetchType = [
  response:Response | null | undefined,
  error:Error | null | undefined,
  isLoading:boolean,
  beginFetch:() =>void
];
const useFetch = (request: RequestInfo, init?: RequestInit):UseFetchType => {
  const [response, setResponse] = useState<null | Response>();
  const [error, setError] = useState<null | Error>();
  const [isLoading, setIsLoading] = useState(false);
  const abortController = new AbortController();
  const beginFetch = async () => {
    setIsLoading(true);
    try {
      const rpd = await fetch(request, {
        ...init,
        signal: abortController.signal,
      });
      setResponse(await rpd?.json());
    } catch (e) {
      if (e.name === 'AbortError') return;
      setError(e);
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(()=>{
    return () => {
      abortController.abort();
    };
  },[])
  return [response, error, isLoading, beginFetch];
}
export default useFetch